
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_TASKS 3000

typedef struct {
    int task;
} Task;

typedef struct {
    Task tasks[MAX_TASKS];
    int count;
    int head;
    int tail;
    int num; // 代表任务数量
    int finished_tasks; // 完成的任务数量
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} ThreadPool;

void* worker(void* arg) {
    ThreadPool* pool = (ThreadPool*)arg;

    while (1) {
        pthread_mutex_lock(&pool->mutex);
        while (pool->count == 0 && pool->num > 0) { // 等待任务或线程池结束信号
            pthread_cond_wait(&pool->cond, &pool->mutex);
        }

        // 处理线程池结束信号
        if (pool->num == -1) {
            pthread_mutex_unlock(&pool->mutex);
            break;
        }

        Task task = pool->tasks[pool->head];
        pool->head = (pool->head + 1) % MAX_TASKS;
        pool->count--;

        pthread_mutex_unlock(&pool->mutex);

        // 判断是否为素数
        int is_prime = 1;
        for (int i = 2; i < task.task; i++) {
            if (task.task % i == 0) {
                is_prime = 0;
                break;
            }
        }

        if (is_prime) {
            printf("%d is a prime number\n", task.task);
        }

        pthread_mutex_lock(&pool->mutex);
        pool->finished_tasks++;
        if (pool->finished_tasks == pool->num) { // 判断是否所有任务都完成了
            pthread_cond_broadcast(&pool->cond); // 发送完成信号
        }
        pthread_mutex_unlock(&pool->mutex);
    }

    return NULL;
}

int main() {
    ThreadPool pool;
    pool.count = 0;
    pool.head = 0;
    pool.tail = 0;
    pool.num = 0;
    pool.finished_tasks = 0;
    pthread_mutex_init(&pool.mutex, NULL);
    pthread_cond_init(&pool.cond, NULL);

    pthread_t threads[3];
    for (int i = 0; i < 3; i++) {
        pthread_create(&threads[i], NULL, worker, (void*)&pool);
    }

    // 添加任务
    for (int i = 1; i <= 3000; i++) {
        pthread_mutex_lock(&pool.mutex);
        while (pool.count == MAX_TASKS) {
            pthread_cond_wait(&pool.cond, &pool.mutex);
        }

        pool.tasks[pool.tail].task = i;
        pool.tail = (pool.tail + 1) % MAX_TASKS;
        pool.count++;
        pool.num++;

        pthread_cond_signal(&pool.cond);
        pthread_mutex_unlock(&pool.mutex);
    }

    pthread_mutex_lock(&pool.mutex);
    while (pool.finished_tasks != pool.num) {
        pthread_cond_wait(&pool.cond, &pool.mutex); // 等待所有任务完成
    }
    pool.num = -1; // 发送线程池结束信号
    pthread_cond_broadcast(&pool.cond); // 唤醒所有等待的线程
    pthread_mutex_unlock(&pool.mutex);

    for (int i = 0; i < 3; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&pool.mutex);
    pthread_cond_destroy(&pool.cond);

    return 0;
}
